use std::{fs::File, io::Write, path::PathBuf};

use clap::Parser;
use compile::compile;

mod command;
mod compile;
mod error;
mod read;

#[derive(Parser)]
#[command(name = "Tiny Asm")]
#[command(version = "1.0")]
#[command(author = "WuJehy <wujehy@139.com>")] 
#[command(version, about= "tiny asm coding", long_about = None)]
struct Cli {
    #[arg(short, long)]
    file: String,
    #[arg(short, long)]
    output: String,
    #[arg(long)]
    hex: bool,
}

fn main() {
    let cli = Cli::parse();
 
    println!("file: {:?}", cli.file);
    println!("output: {:?}", cli.output);
    println!("hex: {:?}", cli.hex);

    let file_path = PathBuf::from(cli.file);
    let reader = read::read_cmds(&file_path).unwrap();

    // let vecs: &Vec<(usize, String)> = &vec![(1usize , "MUL R0, R13, R14".to_string()) ,(2, "ADD R0, R0, R15".to_string()) ];

    let codes = match compile(&reader) {
        Ok(codes) => codes,
        Err(err) => {
            // 编译错误
            println!("compile error : {:?}", err);
            return;
        }
    };

    let output_string = if cli.hex {
        // 输出hex 格式
        let tohex: String = codes.iter().map(|bytes| format!("{:02x}", bytes)).collect();

        // 输出hex
 
        tohex.as_bytes().to_vec()
 
    } else {
        let to_bytes: Vec<u8> = codes
            .iter()
            .flat_map(|x| x.to_le_bytes().to_vec()) // 大端字节序
            .collect();
        to_bytes
    };

    let mut file = match File::create(cli.output) {
        Ok(f) => f,
        Err(err) => {
            println!("output file error : {:?}", err);
            return;
        }
    };

    match file.write_all(&output_string) {
        Ok(_) => {
            println!("compile success!");
        }
        Err(err) => {
            println!("save file error : {:?}", err);
            return;
        }
    };

    return;
}
